# -*- coding: utf-8 -*-
'''
@author: olivia.dou
Created on: 3/19/2021 13:06
desc:
'''
import logging
import traceback

from util.db_util import execute_query


def get_std_col_infos(**kwargs):
    """查找标准化字段信息列表

    :param kwargs:
        | std_col_name: 字段标准名称（编码）
        | parent_id: 父级字段id
        | tbl_name: 标准化表名

    :return: 标准化字段信息列表
    """
    try:
        sub_str = ""
        for arg in kwargs.keys():
            if type(kwargs[arg]) is str and (kwargs[arg].startswith('%') or kwargs[arg].endswith('%')):
                sub_str = sub_str + "and %s like '%s'"%(arg,kwargs[arg])
            else:
                sub_str = sub_str + "and %s = '%s'"%(arg,kwargs[arg])

        sub_str = sub_str.lstrip("and")
        #sql = "SELECT * FROM `t_das_std_tbl_col` WHERE `std_col_name`='%s' %s" % (std_col_name, sub_str)
        sql = "SELECT * FROM `t_das_std_tbl_col` WHERE %s" % sub_str
        results = execute_query(sql, result_type='dict')
        return results
    except Exception as e:
        logging.error("get_std_tbl_col_info: %s"%e)


def get_std_col_info(tbl_name, parent_col_id=-1, **kwargs):
    """获取标准化字段信息

    :param tbl_name: 标准化表名
    :param parent_col_id: 父字段id
    :param kwargs:
        | std_col_name：标准化字段名
        | diaplay_name：显示名称
        | std_field: 存储字段

    :return: 标准化字段信息
    """
    if parent_col_id==-1:
        parent_col_sub = " and parent_id is null"
    else:
        parent_col_sub = " and parent_id =%s"%parent_col_id


    field_specifier = ""
    for kwarg in kwargs:
        field_specifier += " and %s='%s'"%(kwarg,kwargs[kwarg])

    sql = "select * from t_das_std_tbl_col where tbl_name='%s' %s %s"\
          %(tbl_name, field_specifier, parent_col_sub)
    try:
        res = execute_query(sql, result_type="dict")
        #data = pd.Series(res[0],index=["id","std_field","unit_id","data_type","biz_code"])
        if len(res)>0:
            return res[0]
        else:
            logging.error("未找到标准化字段信息")
            return {}
    except Exception as e:
        logging.error("get_std_col_info:%s"%e)
        traceback.print_exc()
        #return pd.Series([])
        return {}


def get_std_col_id(**kwargs):
    """获取标准化字段id

    :param kwargs: 同get_std_tbl_col_info

    :return: 标准化字段id
    """
    infos= get_std_col_infos(**kwargs)
    if len(infos) > 0:
        std_col_info = infos[0]
        if std_col_info != {}:
            return std_col_info['id']
        else:
            return -1
    else:
        return None


def get_std_output_col_specified_params(tbl_name, arg="id"):
    """获取指定标准表中的输出字段的指定参数的列表，默认为id列表

    :param name: 标准表名称

    :return: 指定标准表中的输出字段指定参数的列表，默认为id列表
    """
    condition = "AND `std_field` not like '%%rv%%'ORDER BY `id` desc" if tbl_name == "t_das_std_data_b" else "ORDER BY `id` desc"
    results = execute_query(
        "SELECT %s FROM `t_das_std_tbl_col` WHERE `is_output` = '1' AND `tbl_name` = '%s'" % (arg, tbl_name)+condition)
    try:
        result = [results[i][0] for i in range(len(results))]
        return result
    except Exception as e:
        logging.error("get_std_output_col_specified_params:%s" % e)
        return None

# def get_std_col_saved_field(std_col_name, **kwargs):
#     """获取标准化字段的存储字段（std_field）
#
#     :param std_col_name: 标准化字段名
#     :param kwargs: 同get_std_tbl_col_info
#
#     :return: 标准化字段的存储字段（std_field）
#     """
#     std_col_info = get_std_col_info(std_col_name, **kwargs)
#     if std_col_info != {}:
#         return std_col_info['std_field']
#     else:
#         return -1

def get_std_col_group_id(group_name):
    """
    根据标准字段分组名称，查询标准字段分组ID
    """
    sql = f'select id from t_das_std_col_group where group_name="{group_name}"'
    try:
        res = execute_query(sql)
        return res[0][0]
    except Exception as e:
        return ""
